package com.example.demo.controller;

import cn.hutool.core.lang.Snowflake;
import com.example.demo.dao.base.QueryWrapper;
import com.example.demo.dao.UserRepository;
import com.example.demo.dto.IdDTO;
import com.example.demo.dto.base.R;
import com.example.demo.model.SysUser;
import com.example.demo.dto.base.BasePage;
import com.example.demo.model.page.PageResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * 2025/10/9
 * wys
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserRepository userRepository;

    /**
     * 用户列表
     */
    @GetMapping("listPage")
    public R<PageResult<SysUser>> listPage(BasePage basePage){
        PageResult<SysUser> sysUserPageResult = userRepository.selectPage(new QueryWrapper<SysUser>()
                        .eq(SysUser::getDelFlag, 0),
                basePage.getPageNum(), basePage.getPageSize());
        return R.ok(sysUserPageResult);
    }

    /**
     * 添加
     *
     * @param sysUser sysUser
     */
    @PostMapping("insert")
    public R<SysUser> insert(@RequestBody SysUser sysUser){
        sysUser.setId(new Snowflake().nextId());
        sysUser.setCreateBy("system");
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setUpdateBy("system");
        sysUser.setUpdateTime(LocalDateTime.now());
        userRepository.insert(sysUser);
        return R.ok(sysUser);
    }

    /**
     * 修改
     * @param sysUser sysUser
     */
    @PostMapping("update")
    public R<SysUser> update(@RequestBody SysUser sysUser){
        sysUser.setUpdateBy("system");
        sysUser.setUpdateTime(LocalDateTime.now());
        userRepository.updateById(sysUser, sysUser.getId());
        return R.ok(sysUser);
    }

    /**
     * 删除
     * @param idDTO idDTO
     */
    @PostMapping("delete")
    public R<Boolean> delete(@RequestBody IdDTO idDTO){
        userRepository.deleteById(idDTO.getId());
        return R.ok(true);
    }

    /**
     * 获取用户
     *
     * @param id id
     */
    @GetMapping("getUser")
    public R<SysUser> getUser(@RequestParam("id")String id){
        return R.ok(userRepository.selectById(id));
    }
}
